<?php
/**
 * 钉钉登录回调处理
 */

session_start();

// 读取配置
$configFile = __DIR__ . '/../../config.php';
$config = [];
if (file_exists($configFile)) {
    $config = include $configFile;
}

$dingtalkConfig = $config['plugins']['dingtalk'] ?? [];

// 检查插件是否启用
if (!isset($dingtalkConfig['enabled']) || !$dingtalkConfig['enabled']) {
    die('钉钉登录插件未启用');
}

// 获取回调参数
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';

// 验证 state 参数防止 CSRF
if (empty($state) || !isset($_SESSION['dingtalk_state']) || $state !== $_SESSION['dingtalk_state']) {
    die('无效的请求');
}

// 清除 state
unset($_SESSION['dingtalk_state']);

if (empty($code)) {
    die('未获取到授权码');
}

$appKey = $dingtalkConfig['app_key'] ?? '';
$appSecret = $dingtalkConfig['app_secret'] ?? '';

if (empty($appKey) || empty($appSecret)) {
    die('钉钉配置不完整');
}

try {
    // 1. 获取 access_token
    $tokenUrl = 'https://oapi.dingtalk.com/gettoken?appkey=' . urlencode($appKey) . '&appsecret=' . urlencode($appSecret);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tokenUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $tokenResult = json_decode($response, true);
    
    if (!isset($tokenResult['access_token'])) {
        die('获取 access_token 失败：' . ($tokenResult['errmsg'] ?? '未知错误'));
    }
    
    $accessToken = $tokenResult['access_token'];
    
    // 2. 使用临时授权码换取用户信息
    $userInfoUrl = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=' . urlencode($appKey) . '&timestamp=' . (time() * 1000) . '&signature=' . generateSignature($appSecret);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $userInfoUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['tmp_auth_code' => $code]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $userInfo = json_decode($response, true);
    
    if (!isset($userInfo['user_info'])) {
        die('获取用户信息失败：' . ($userInfo['errmsg'] ?? '未知错误'));
    }
    
    // 3. 获取用户详细信息
    $unionid = $userInfo['user_info']['unionid'] ?? '';
    $nick = $userInfo['user_info']['nick'] ?? '';
    
    if (empty($unionid)) {
        die('未获取到用户唯一标识');
    }
    
    // 4. 根据 unionid 获取 userid（需要企业 corpid）
    $corpId = $dingtalkConfig['corp_id'] ?? '';
    if (!empty($corpId)) {
        $useridUrl = 'https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=' . urlencode($accessToken);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $useridUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['unionid' => $unionid]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $useridResult = json_decode($response, true);
        
        if (isset($useridResult['result']['userid'])) {
            $userid = $useridResult['result']['userid'];
            
            // 获取用户详细信息
            $detailUrl = 'https://oapi.dingtalk.com/topapi/v2/user/get?access_token=' . urlencode($accessToken);
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $detailUrl);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['userid' => $userid]));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            
            $response = curl_exec($ch);
            curl_close($ch);
            
            $detailResult = json_decode($response, true);
            
            if (isset($detailResult['result'])) {
                $nick = $detailResult['result']['name'] ?? $nick;
            }
        }
    }
    
    // 5. 检查是否与管理员配置中的钉钉号匹配
    $adminDingtalkId = $config['admin_user']['dingtalk_id'] ?? '';
    
    if (empty($adminDingtalkId)) {
        die('管理员未配置钉钉号，无法使用钉钉登录');
    }
    
    // 匹配 unionid 或 userid
    $isAuthorized = false;
    if ($adminDingtalkId === $unionid) {
        $isAuthorized = true;
    } elseif (isset($userid) && $adminDingtalkId === $userid) {
        $isAuthorized = true;
    }
    
    if (!$isAuthorized) {
        die('该钉钉账号未授权登录，请联系管理员<br>当前 UnionID: ' . htmlspecialchars($unionid) . (isset($userid) ? '<br>UserID: ' . htmlspecialchars($userid) : ''));
    }
    
    // 6. 设置登录 session
    $_SESSION['logged_in'] = true;
    $_SESSION['username'] = $config['admin_user']['username']; // 使用管理员配置的用户名
    $_SESSION['dingtalk_unionid'] = $unionid;
    $_SESSION['login_type'] = 'dingtalk';
    
    // 7. 跳转到首页
    header('Location: ../../index.php');
    exit;
    
} catch (Exception $e) {
    die('登录失败：' . $e->getMessage());
}

/**
 * 生成钉钉签名
 */
function generateSignature($secret) {
    $timestamp = time() * 1000;
    $stringToSign = $timestamp;
    return base64_encode(hash_hmac('sha256', $stringToSign, $secret, true));
}
